package com.ymatou.shop.ui.activity.seller;

import java.io.IOException;
import java.util.ArrayList;

import com.ymatou.shop.R;
import com.ymatou.shop.api.ApiRequest;
import com.ymatou.shop.cache.RequestInfo;
import com.ymatou.shop.cache.exception.CacheException;
import com.ymatou.shop.location.Location;
import com.ymatou.shop.location.LocationListener;
import com.ymatou.shop.location.LocationManager;
import com.ymatou.shop.ui.activity.BaseActivity;
import com.ymatou.shop.ui.activity.seller.AddProductActivity;
import com.ymatou.shop.util.GlobalUtil;
import com.ymatou.shop.util.StringUtil;

import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class CameraActivity extends BaseActivity implements SensorEventListener {
	private SurfaceView previewSV;
	private Camera camera;
	private LinearLayout previewLayout;
	private View cameraLayout;
	private ArrayList<Bitmap> mBitmaps;
	private TextView mTextView, mTextView2, mTextView3;
	public static final int REQUEST_CODE_IMPORT_LOCAL_IMAGE = 0;
	public static final int REQUEST_ID_CREATE_ACTIVITY = 0;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.camera_activity);

		setupViews();
	}

	@Override
	protected void setupViews() {

		mBitmaps = new ArrayList<Bitmap>();

		SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
		sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_NORMAL);

		
		
		if (getAccount().getLocation() != null && getAccount().getLocation().getLatitude() > 0){
			showCamera();
		}else {
			openLocation();
			
//			setupLocationView();
		}
		
		

		super.setupViews();
	}
	
	private void openLocation(){
		LocationManager.getInstance(this).getLocation(new LocationListener() {

			@Override
			public void onReceiveLocation(Location location) {
				if (location != null && StringUtil.isNotEmpty(location.getCity())) {
					getAccount().setLocation(location);
					createActivity();
					
				}else {
					new AlertDialog.Builder(CameraActivity.this)
					
					.show();
				}

			}
		});
	}
	
	/**
	 * 定位成功后开始新活动
	 */
	private void createActivity() {
		RequestInfo request = ApiRequest.createActivity("" + getAccount().getLocation().getLatitude() +","+getAccount().getLocation().getLongitude());
		getCacheManager().register(REQUEST_ID_CREATE_ACTIVITY, request, this);
	}

@Override
public void onCacheSuccess(int requestId, RequestInfo requestInfo, Object response) {
	if (requestId == REQUEST_ID_CREATE_ACTIVITY){
		mTextView.setText(getString(R.string.location_success));
		mTextView2.setText(getString(R.string.location_textview, getAccount().getLocation().getCity() + getAccount().getLocation().getAddress()));
		mTextView2.setVisibility(View.VISIBLE);
		mTextView3.setVisibility(View.VISIBLE);
	}
  super.onCacheSuccess(requestId, requestInfo, response);
}

@Override
public void onCacheFailed(int requestId, RequestInfo requestInfo, CacheException error) {
  // TODO Auto-generated method stub
  super.onCacheFailed(requestId, requestInfo, error);
}

	private void setupLocationView() {
		mTextView = (TextView) findViewById(R.id.location_hint);
		mTextView2 = (TextView) findViewById(R.id.location_textview);
		mTextView3 = (TextView) findViewById(R.id.new_textview);
		mTextView3.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showCamera();

			}
		});
	}

	private void showCamera() {

		findViewById(R.id.location_layout).setVisibility(View.GONE);
		findViewById(R.id.top_layout).setVisibility(View.GONE);

		previewLayout = (LinearLayout) findViewById(R.id.preview_layout);
		cameraLayout = (LinearLayout) findViewById(R.id.camera_layout);
		cameraLayout.setVisibility(View.VISIBLE);
		previewSV = (SurfaceView) findViewById(R.id.previewSV);
		previewSV.setVisibility(View.VISIBLE);
		previewSV.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		previewSV.getHolder().addCallback(new MyCallback());
		
		findViewById(R.id.back_button).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				onBackPressed();
				
			}
		});
	}

	private class MyCallback implements Callback {
		public void surfaceCreated(SurfaceHolder holder) {
			try {
				camera = Camera.open();

				Parameters params = camera.getParameters();
				System.out.println(params.flatten());
				//				params.setPreviewSize(800, 480);
				//				params.setPictureSize(800, 480);
				params.setJpegQuality(100);
				camera.setParameters(params);

				camera.setDisplayOrientation(90);

				Parameters mParameters = camera.getParameters();
				//				mParameters.set("orientation", "portrait");
				mParameters.setRotation(180);
				camera.setParameters(mParameters);

				camera.setPreviewDisplay(previewSV.getHolder());
				camera.startPreview();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		public void surfaceDestroyed(SurfaceHolder holder) {
			if (camera != null) {
				camera.stopPreview();
				camera.release();
				camera = null;
			}
		}

		public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
		}
	}

	private View mView;

	public void onClickStartCamera(View view) {
		if (mBitmaps != null && mBitmaps.size() > 5) {
			GlobalUtil.shortToast(this, "最多只可上传6张图片");
			return;
		}
		mView = view;
		mView.setEnabled(false);
		camera.autoFocus(new MyAutoFocusCallback());
	}

	public void onClickImportLocalImage(View view) {
		Intent intent = new Intent(Intent.ACTION_PICK, null);
		intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
		startActivityForResult(intent, REQUEST_CODE_IMPORT_LOCAL_IMAGE);
	}

	public void onClickNextStep(View view) {
		if (mBitmaps == null || mBitmaps.size() == 0) {
			new AlertDialog.Builder(view.getContext()).setMessage(R.string.product_picture_not_null).setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();

				}
			}).show();
			return;
		}

		Intent mIntent = new Intent(this, AddProductActivity.class);
		mIntent.putExtra(AddProductActivity.BITMAPS_KEY, mBitmaps);
		startActivity(mIntent);
		finish();
	}

	private class MyAutoFocusCallback implements AutoFocusCallback {
		public void onAutoFocus(boolean success, Camera camera) {
			camera.takePicture(null, null, new MyPictureCallback());
		}
	}

	private class MyPictureCallback implements PictureCallback {
		public void onPictureTaken(byte[] data, Camera camera) {
			//			try {

			final BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = true;
			BitmapFactory.decodeByteArray(data, 0, data.length, options);

			// Calculate inSampleSize
			options.inSampleSize = calculateInSampleSize(options, (int) (80 * 1.5), (int) (60 * 1.5));

			// Decode bitmap with inSampleSize set
			options.inJustDecodeBounds = false;
			Bitmap mBitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
			Matrix matrix = new Matrix();
			matrix.postRotate(getDegree());
			mBitmap = Bitmap.createBitmap(mBitmap, 0, 0, mBitmap.getWidth(), mBitmap.getHeight(), matrix, true);

			addImageView(mBitmap);
			camera.startPreview();
			mView.setEnabled(true);
		}
	}

	private void addImageView(final Bitmap b) {
		mBitmaps.add(b);
		final View view = View.inflate(this, R.layout.camera_item, null);
		ImageView mImageView = (ImageView) view.findViewById(R.id.product_imageview);
		mImageView.setImageBitmap(b);
		view.findViewById(R.id.delete_preview).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				previewLayout.removeView(view);
				mBitmaps.remove(b);
			}
		});
		previewLayout.addView(view);
	}

	private int getDegree() {

		int tempDegree = 0;
		if (z <= 45 && z >= -45) {

			tempDegree = -90;
		} else if (z < -45 && z >= -90) {
			tempDegree = 0;
		} else if (z > 45 && z <= 90) {
			tempDegree = 180;
		}
		return tempDegree;
	}

	public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
		// Raw height and width of image
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;

		if (height > reqHeight || width > reqWidth) {
			if (width > height) {
				inSampleSize = Math.round((float) height / (float) reqHeight);
			} else {
				inSampleSize = Math.round((float) width / (float) reqWidth);
			}

			// This offers some additional logic in case the image has a strange
			// aspect ratio. For example, a panorama may have a much larger
			// width than height. In these cases the total pixels might still
			// end up being too large to fit comfortably in memory, so we should
			// be more aggressive with sample down the image (=larger
			// inSampleSize).

			final float totalPixels = width * height;

			// Anything more than 2x the requested pixels we'll sample down
			// further.
			final float totalReqPixelsCap = reqWidth * reqHeight * 2;

			while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
				inSampleSize++;
			}
		}
		return inSampleSize;
	}

	public static int readPictureDegree(String path) {
		int degree = 0;
		try {
			ExifInterface exifInterface = new ExifInterface(path);
			int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
			switch (orientation) {
			case ExifInterface.ORIENTATION_ROTATE_90:
				degree = 90;
				break;
			case ExifInterface.ORIENTATION_ROTATE_180:
				degree = 180;
				break;
			case ExifInterface.ORIENTATION_ROTATE_270:
				degree = 270;
				break;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return degree;
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}

	private float z;

	@Override
	public void onSensorChanged(SensorEvent event) {
		if (event.sensor.getType() == Sensor.TYPE_ORIENTATION) {
			z = event.values[SensorManager.DATA_Z];
		}

	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case REQUEST_CODE_IMPORT_LOCAL_IMAGE:
			String path = getFilePath(data);

			int degree = readPictureDegree(path);

			final BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = true;
			BitmapFactory.decodeFile(path, options);

			// Calculate inSampleSize
			options.inSampleSize = calculateInSampleSize(options, (int) (80 * 1.5), (int) (60 * 1.5));

			// Decode bitmap with inSampleSize set
			options.inJustDecodeBounds = false;
			Bitmap mBitmap = BitmapFactory.decodeFile(path, options);

			Matrix matrix = new Matrix();
			matrix.postRotate(degree);
			mBitmap = Bitmap.createBitmap(mBitmap, 0, 0, mBitmap.getWidth(), mBitmap.getHeight(), null, true);

			addImageView(mBitmap);

			break;

		default:
			break;
		}
	}

	private String getFilePath(Intent data) {
		String filePath = null;
		if (data != null) {
			Uri uri = data.getData();

			if (uri != null) {

				ContentResolver contentResolver = getContentResolver();
				Cursor cursor = contentResolver.query(uri, null, null, null, null);
				if (cursor == null) {
					return filePath;
				}
				cursor.moveToFirst();
				if (cursor != null) {
					cursor.moveToFirst();
					int index = cursor.getColumnIndex("_data");
					if (index > -1) {
						if (cursor.getString(index) != null) {
							filePath = cursor.getString(index);
						}
					}
					cursor.close();
				}

			}
		}

		return filePath;
	}

	@Override
	public void finish() {
		if (camera != null) {
			camera.stopPreview();
			camera.release();
			camera = null;
		}
		super.finish();
	}
}